package com.gome.ocean.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gome.framework.util.SystemInfoUtil;

/**
 * 获取本机IP
 *
 * @author haqiaolong 2016年2月23日 下午1:59:42
 * @since 5.0.0
 */
public final class AddressUtils {

    private static final Logger  logger          = LoggerFactory.getLogger(AddressUtils.class);
    private static final String  LOCALHOST_IP    = "127.0.0.1";
    private static final String  EMPTY_IP        = "0.0.0.0";
    private static final Pattern IP_PATTERN      = Pattern.compile("[0-9]{1,3}(\\.[0-9]{1,3}){3,}");
    private static final Pattern IP_PORT_PATTERN = Pattern.compile("((\\d+\\.){3}\\d+)\\:(\\d+)");
    private static String        LOCAL_IP;
    private static String        LOCAL_HOSTNAME;
    private static String        LOCAL_PORT;

    static {
        InetAddress address = getHostAddress();
        LOCAL_IP = address == null ? null : address.getHostAddress();
        LOCAL_HOSTNAME = address == null ? null : address.getHostName();
        LOCAL_PORT = SystemInfoUtil.getServerPort();

    }

    private static boolean isValidHostAddress(InetAddress address) {
        if (address == null || address.isLoopbackAddress()) {
            return false;
        }
        String name = address.getHostAddress();
        return (name != null && !EMPTY_IP.equals(name) && !LOCALHOST_IP.equals(name)
                && IP_PATTERN.matcher(name).matches() && name.startsWith("10."));
    }

    public static String getHostIpAndPort() {
        return getHostIp().concat(":").concat(getHostPort());
    }

    public static String getHostPort() {
        return LOCAL_PORT;
    }

    public static String getHostIp() {
        return LOCAL_IP;
    }

    public static boolean isLocalIp(String ipaddr) {
        return LOCAL_IP.equals(ipaddr);
    }

    public static String getIpPort(String ipaddr) {
        Matcher m = IP_PORT_PATTERN.matcher(ipaddr);
        while (m.find()) {
            return m.group();
        }
        return null;
    }

    public static String getHostName() {
        return LOCAL_HOSTNAME;
    }

    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().indexOf("linux") != -1;
    }

    public static boolean isWindons() {
        return System.getProperty("os.name").toLowerCase().indexOf("win") != -1;
    }

    public static InetAddress getHostAddress() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            if (interfaces != null) {
                while (interfaces.hasMoreElements()) {
                    try {
                        NetworkInterface network = interfaces.nextElement();
                        Enumeration<InetAddress> addresses = network.getInetAddresses();
                        if (addresses != null) {
                            while (addresses.hasMoreElements()) {
                                try {
                                    InetAddress address = addresses.nextElement();
                                    if (isValidHostAddress(address)) {
                                        return address;
                                    }
                                } catch (Throwable e) {
                                    logger.warn("Failed to retriving network card ip address. cause:" + e.getMessage());
                                }
                            }
                        }
                    } catch (Throwable e) {
                        logger.warn("Failed to retriving network card ip address. cause:" + e.getMessage());
                    }
                }
            }
        } catch (Throwable e) {
            logger.warn("Failed to retriving network card ip address. cause:" + e.getMessage());
        }
        logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");
        return null;
    }
}
